package com.ayf.payment.game.api.service.impl;

import com.ayf.payment.game.api.dto.MerchantAccountOptions;
import com.ayf.payment.game.api.entity.MerchantAccount;
import com.ayf.payment.game.api.exception.ParameterException;
import com.ayf.payment.game.api.mapper.MerchantAccountMapper;
import com.ayf.payment.game.api.service.MerchantAccountService;
import com.swwx.charm.commons.lang.utils.LogPortal;
import com.swwx.charm.zookeeper.lock.DistributedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service
public class MerchantAccountServiceImpl implements MerchantAccountService {

    @Resource
    private MerchantAccountMapper merchantAccountMapper;

    @Autowired
    protected DistributedLock distributedLock;

    @Override
    public MerchantAccount selectOne(Integer merchantId) {
        if (merchantId == null) {
            throw new ParameterException("商户号不能为空");
        }
        MerchantAccount merchantAccount = new MerchantAccount();
        merchantAccount.setMerchantId(merchantId);
        return merchantAccountMapper.selectOne(merchantAccount);
    }

    @Override
    @Transactional
    public void updateMerchantAccount(MerchantAccountOptions accountOptions) {
        String lockName = "zk-merchantAccount" + accountOptions.getMerchantId();
        try {
               synchronized(lockName){
                LogPortal.info("商户[{}]账户操作[{}]",accountOptions.getMerchantId(), accountOptions.getOptionType());
                MerchantAccount merchantAccount=new MerchantAccount();
                merchantAccount.setMerchantId(accountOptions.getMerchantId());
                merchantAccount.setBalance(accountOptions.getOptionCash()==null?BigDecimal.ZERO:accountOptions.getOptionCash());
                merchantAccount.setFreezing(accountOptions.getFreezing()==null?BigDecimal.ZERO:accountOptions.getFreezing());
                merchantAccount.setCashWithdrawal(accountOptions.getCashWithdrawal()==null?BigDecimal.ZERO:accountOptions.getCashWithdrawal());
                merchantAccount.setCashIn(accountOptions.getCashWithdrawalIng()==null?BigDecimal.ZERO:accountOptions.getCashWithdrawalIng());
                merchantAccount.setSplitAmt(accountOptions.getSplitAmt()==null?BigDecimal.ZERO:accountOptions.getSplitAmt());
                merchantAccountMapper.updateMerchantAccount(merchantAccount);
            }
        } catch (Exception e) {
            LogPortal.error("商户[{}]账户操作[{}] 异常", e, accountOptions.getMerchantId(), accountOptions.getOptionType());
        }
    }
}


